#include "apue.h"

#include <sys/msg.h>

int main()
{
  int msqid;
  pid_t pid;
  struct mymesg {
    long mtype;
    char mtext[512];
  } msg;

  // 创建消息队列，指定读写权限
  msqid = msgget(IPC_PRIVATE, IPC_CREAT | S_IWUSR | S_IRUSR);
  if (msqid < 0) {
    printf("msgget failed.\n");
  } else {
    printf("msqid=%d\n", msqid);
  }

  if ((pid = fork()) < 0) {
    printf("fork failed.\n");
  } else if (pid > 0) {
    // parent
    msg.mtype = 1;
    while (1) {
      msg.mtext[0]++;
      printf("parent: %d\n", msg.mtext[0]);
      int r = msgsnd(msqid, &msg, sizeof(struct mymesg), IPC_NOWAIT);
      if (r < 0) {
        printf("parent: msgsnd failed.\n");
      }
      sleep(1);
    }
    exit(0);
  } else {
    // child
    ssize_t size;
    while (1) {
      size = msgrcv(msqid, &msg, sizeof(struct mymesg), 0, 0);
      if (size < 0) {
        printf("child : msgrcv failed.\n");
      } else {
        printf("child: %d\n", msg.mtext[0]);
      }
    }
    exit(0);
  }

  return 0;
}